#include "joystick.h"

#include <OISException.h>
#include <iostream>

Joystick::Joystick(QObject *parent)
  : InputDevice(parent), _joystick(NULL)
{
}

void Joystick::init(OIS::InputManager* mgr)
{
  try
  {
    _joystick = (OIS::JoyStick*)mgr->createInputObject(OIS::OISJoyStick, true);
    if (_joystick == NULL)
      return;
    _joystick->setEventCallback(this);
    std::cout << "\n\nCreating Joystick "
      << "\n\tAxes: " << _joystick->getNumberOfComponents(OIS::OIS_Axis)
      << "\n\tSliders: " << _joystick->getNumberOfComponents(OIS::OIS_Slider)
      << "\n\tPOV/HATs: " << _joystick->getNumberOfComponents(OIS::OIS_POV)
      << "\n\tButtons: " << _joystick->getNumberOfComponents(OIS::OIS_Button)
      << "\n\tVector3: " << _joystick->getNumberOfComponents(OIS::OIS_Vector3) << std::endl;
  }
  catch(OIS::Exception &ex)
  {
    std::cout << "\nException raised on joystick creation: " << ex.eText << std::endl;
    _joystick = NULL;
  }
}

bool Joystick::buttonPressed(const OIS::JoyStickEvent &, int)
{
  return true;
}

bool Joystick::buttonReleased(const OIS::JoyStickEvent &, int button)
{
  if (button == 1)
  {
    emit key(Ak_Enter);
  }
  if (button == 3)
  {
    emit key(Ak_Back);
  }
  return true;
}

bool Joystick::axisMoved(const OIS::JoyStickEvent &arg, int axis)
{
  int pos = arg.state.mAxes[axis].abs;
  if (axis == 0) // Up / Down
  {
    if (pos < 0) // Up
      _currentKey = Ak_Up;
    else if (pos > 0) // Down
      _currentKey = Ak_Down;
  }
  else // Left/Right
  {
    if (pos < 0) // Left
      _currentKey = Ak_Left;
    else if (pos > 0) // Right
      _currentKey = Ak_Right;
  }

  if (pos != 0)
    startKeyEmit();
  else
    stopKeyEmit();
  return true;
}

void Joystick::capture()
{
  if (_joystick == NULL)
    return;
  _joystick->capture();
}
